import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)


export default new Vuex.Store({
  state: {
    token: sessionStorage.getItem('token') || false,
    userType: sessionStorage.getItem('type') || '',
    userId: sessionStorage.getItem('userId') || '',
    userName: sessionStorage.getItem('userName') || ''
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
      sessionStorage.setItem('token', token)
    },
    SET_USER_TYPE: (state, type) => {
      state.userType = type
      sessionStorage.setItem('type', type)
    },
    SET_USER_ID: (state, id) => {
    // 确保id有效时才存储
    if (id !== undefined && id !== null && id !== 'undefined') {
      state.userId = id;
      sessionStorage.setItem('userId', id);
    }
  },
  SET_USER_NAME: (state, name) => {
    // 确保name有效时才存储
    if (name !== undefined && name !== null && name !== 'undefined') {
      state.userName = name;
      sessionStorage.setItem('userName', name);
    }
  },
    CLEAR_USER: (state) => {
      state.token = false
      state.userType = ''
      state.userId = ''
      state.userName = ''
      sessionStorage.clear()
    }
  },
  actions: {
    login({ commit }, { token, type, id, name }) {
      commit('SET_TOKEN', token)
      commit('SET_USER_TYPE', type)
      commit('SET_USER_ID', id)
      commit('SET_USER_NAME', name)
    },
    logout({ commit }) {
      commit('CLEAR_USER')
    }
  },
  getters: {
    isAuthenticated: state => state.token,
    userType: state => state.userType,
    userId: state => state.userId,
    userName: state => state.userName
  }
})